﻿#include "canvasdesktop.h"
#include <QScrollBar>
#include <QDebug>
#include "mainscene.h"

extern CANVAS_OPERATION g_currentOperation;

CanvasDesktop::CanvasDesktop(QGraphicsScene *scene, QWidget *parent)
    : QGraphicsView(scene,parent)
{
    //setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); // 去掉滚动条
    //setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    setViewportUpdateMode(QGraphicsView::FullViewportUpdate);
    setRenderHints(QPainter::Antialiasing);

    /*以鼠标中心进行缩放*/
    setMouseTracking(true);
    setTransformationAnchor(QGraphicsView::AnchorUnderMouse);
    setResizeAnchor(QGraphicsView::AnchorUnderMouse);
    /********************/
    m_scalingOffset=1;
    viewport()->setCursor(Qt::ArrowCursor);
}


void CanvasDesktop::drawBackground(QPainter * painter, const QRectF & rect)
{
    //绘制背景
    int wid = this->geometry().width();
    int hei = this->geometry().height();
    m_ptCenter = this->mapToScene(wid / 2, hei / 2);
    QPixmap pix(wid, hei);
    QPainter pter(&pix);
    QColor clr_white(Qt::white);
    QColor clr_gray(240, 240, 240, 240);
    int spacing = 15;
    QColor useColor;
    for (int i = 0; i <= floor(wid / spacing); i++)
    {
        for (int j = 0; j <= floor(hei/ spacing); j++)
        {
            useColor = ((i + j) % 2 == 0 ? clr_white : clr_gray);
            pter.fillRect(i*spacing, j*spacing, spacing, spacing, useColor);
        }
    }
    painter->drawImage(rect, pix.toImage());
    QRectF sceneRect = this->sceneRect();
    painter->fillRect(sceneRect,scene()->backgroundBrush());
}

void CanvasDesktop::wheelEvent(QWheelEvent *event)
{
    QGraphicsView::wheelEvent(event);
    int wheelValue = event->angleDelta().y();
    m_ratio = (double)wheelValue / (double)1200 + 1;
    scale(m_ratio,m_ratio);//缩放函数，参数表示缩放的倍数
}

void CanvasDesktop::paintEvent(QPaintEvent *event)
{
    QGraphicsView::paintEvent(event);
    QPainter painter(this->viewport());
    viewport()->update();
}

void CanvasDesktop::focusInEvent(QFocusEvent *event) {
    QGraphicsView::focusInEvent(event);
    viewport()->setCursor(Qt::ArrowCursor);
}

void CanvasDesktop::mousePressEvent(QMouseEvent *event) {
    QGraphicsView::mousePressEvent(event);
    if(g_currentOperation == CANVAS_OPERATION_CHOOSE){
        viewport()->setCursor(Qt::ArrowCursor);
    }else{
        viewport()->setCursor(Qt::CrossCursor);
    }
}

void CanvasDesktop::mouseMoveEvent(QMouseEvent *event) {
    QGraphicsView::mouseMoveEvent(event);
}

void CanvasDesktop::mouseReleaseEvent(QMouseEvent *event) {
    QGraphicsView::mouseReleaseEvent(event);
    viewport()->setCursor(Qt::ArrowCursor);
}

